package 链表;

import java.util.ArrayList;
import java.util.Stack;

public class Solution7 {
    //https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
    //思路：栈调到相加的位置
    public ListNode addInList (ListNode head1, ListNode head2) {
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null) {
            stack1.push(cur1);
            cur1 = cur1.next;
        }
        while (cur2 != null) {
            stack2.push(cur2);
            cur2 = cur2.next;
        }
        int addFlag = 0;
        ListNode head = null;
        while (!stack1.isEmpty() || !stack2.isEmpty()) {
            int add1 = 0, add2 = 0;
            if(!stack1.isEmpty()) {
                add1 = stack1.pop().val;
            }
            if(!stack2.isEmpty()) {
                add2 = stack2.pop().val;
            }
            int sum = add1 + add2 + addFlag;
            if(sum >= 10) {
                addFlag = 1;
                ListNode cur = new ListNode(sum - 10);
                cur.next = head;
                head = cur;
            }else {
                addFlag = 0;
                ListNode cur = new ListNode(sum);
                cur.next = head;
                head = cur;
            }
        }
        if(addFlag == 1) {
            ListNode cur = new ListNode(1);
            cur.next = head;
            head = cur;
        }
        return head;
    }
    //题解：反转链表到相加的位置
}
